import React, { useEffect, useState } from 'react';
import './index.less'
import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import request from '@/api'
import { useNavigate } from 'react-router-dom'
import { passwordEncryption } from "@/utils/passwordEncryption";
import { encrypt, decrypt } from "@/utils/aes";
import loginBg from "@/assets/images/8.png"
import { setCookies, getCookies, removeCookies } from '@/utils/cookies'

import getMenu from "@/routes/routerConfig";
//用于获取状态
import store from "@/redux/store";

const Login = () => {
  const navigate = useNavigate()
  // 登录按钮loading
  let [loading, setLoading] = useState(false)
  let title = window.envConfig.ROOT_APP_NAME
  let [submitLoginName, setSubmitLoginName] = useState('登录')
  let [form] = Form.useForm();
  let [checked, setChecked] = useState(false);

  // 确认登录
  const onFinish = async (userInfo) => {
    setLoading(true)
    setSubmitLoginName('正在登录...')
    
    // 真实登录
    // userInfo.password = passwordEncryption(userInfo.password) //密码加密
    request.getLogin(userInfo).then(res => {
      console.log(res);
      if (res.data.ret == 0) {
        //  存储用户信息 角色信息
        localStorage.setItem(window.envConfig['ROOT_APP_INFO'], JSON.stringify({
          userInfo: userInfo,
        }))
        navigate('/rules')
        message.success(res.data.msg)
        // getMenu().then(res => {
        //   //通知reducer页面数据变化了
        //   store.dispatch({
        //     type: 'reload',
        //     data: true
        //   })

        //   navigate('/dashboard/analysis')
        //   // 判断是否是登录页进入首页
        //   localStorage.setItem("ZhuXiaoJia", true)
        // })
      }else {
        message.error(res.data.msg)
      }
      setLoading(false)
      setSubmitLoginName('登录')
    }).catch(error => {
      console.log(error)
      setLoading(false)
      setSubmitLoginName('登录')
    })

  };

  useEffect(() => {
    const appInfo = JSON.parse(localStorage.getItem(window.envConfig['ROOT_APP_INFO']))
    // 检查 cookie 中是否存在 user_id
    const userIdCookie = getCookies('user_id');

    // 如果存在 appInfo，并且 user_id cookie 存在，则跳转到 /rules
    if (appInfo && userIdCookie) {
      navigate('/rules');
    }
    const loginChecked = getCookies('loginChecked')
    if (loginChecked) {
      let { checked, password, user_id } = JSON.parse(decrypt(loginChecked))
      setChecked(checked)
      form.setFieldsValue({
        user_id, password
      })
    }
  }, [checked]);

  // 记住密码
  const onChange = async (e) => {
    const loginChecked = getCookies('loginChecked')
    if (loginChecked) {
      setChecked(false)
      removeCookies("loginChecked", 7)
    } else {
      let values = await form.validateFields();
      values.checked = e.target.checked
      setChecked(e.target.checked)
      setCookies('loginChecked', encrypt(JSON.stringify(values)), 7) //7天有效期
    }
  };

  return (
    <div className="login" style={{ backgroundImage: `url(${loginBg})` }}>
      <div className="login-content-box">
        <section className="login-content">
          <div className="haed">
              {title}
          </div>
          <div>
            <Form
              name="normal_login"
              className="login-form"
              form={form}
              initialValues={{ remember: true }}
              onFinish={onFinish}
            >
              <Form.Item
                name="user_id"
                rules={[
                  { required: true, message: '请输入用户名!' },
                ]}
              >
                <Input size="large" placeholder="用户名" prefix={<UserOutlined className="site-form-item-icon" />} allowClear />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, whitespace: false, message: '请输入登录密码!' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="密码" size="large"

                />
              </Form.Item>
              <Checkbox onChange={onChange} checked={checked} >记住密码</Checkbox>

              <Form.Item>
                <Button type="primary" htmlType="submit" className="login-form-button" loading={loading} disabled={loading}>
                  {submitLoginName}
                </Button>
              </Form.Item>
            </Form>
          </div>
          <div className='school-exchange'>
            厦门大学x中国金融期货交易所
          </div>
        </section>
      </div>
      <Author />
    </div>
  );

}

function Author() {
  return (
    <div className="author">
      {/* <p> Ant Big Data monitoring system © 2022 <a href="https://gitee.com/jiangsihan/React-admin" target="_blank">React-Ant-Admin@v2.0.0</a></p>

      <p>技术支持：<a href="https://jiangsihan.cn/" target="_blank">前端江太公</a> @ 江一铭 <a href="mailto:jiangyiming621@163.com"> Send email to Yiming-Jiang</a> 初始账号密码：admin 123456</p> */}
    </div>
  )
}

export default Login
